package com.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
public class FileController2 {
   @RequestMapping("upload")
   public String upload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException {
      String filename = file.getOriginalFilename();
      String realPath = request.getServletContext().getRealPath("upload");
      File file1=new File(realPath);
      if (!file1.exists()){
         file1.mkdir();
      }

      InputStream inputStream = file.getInputStream();
      FileOutputStream outputStream=new FileOutputStream(new File(file1,filename));

      int len;
      byte[] buffer=new byte[1024];
      while((len=inputStream.read(buffer))!=-1){
         outputStream.write(buffer,0,len);
      }

      outputStream.close();
      inputStream.close();
      return null;
   }

   @RequestMapping("download")
   public String download(HttpServletRequest request,HttpServletResponse response) throws IOException {
      String fileName="HD.jpg";
      String realPath = request.getServletContext().getRealPath("upload");

      response.reset();
      response.setCharacterEncoding("UTF-8");
      response.setContentType("multipart/form-data");
      response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

      ServletOutputStream outputStream = response.getOutputStream();
      File file=new File(fileName,realPath);
      FileInputStream inputStream=new FileInputStream(file);

      int len;
      byte[] buffer=new byte[1024];
      while((len=inputStream.read(buffer))!=-1){
         outputStream.write(buffer,0,len);
      }
      outputStream.close();
      inputStream.close();
      return null;
   }

}
